/**
 * Created by oneminute on 7/27/14.
 */


var assert = require("assert");
var should = require("should");
var logger = require("../../lib/utils/logger");
var testutils = require("../testutils");
var lz = require("../../lib/utils/modules")();
var httpMocks = require("../lib/http-mock");
var async = require("async");
var login = require("../../routes/login");

describe("测试routes/login模块。", function () {
    var users = [];

    before(function (done) {
        var user = new lz.User({
            email: {
                email: "login_req_0001@lz.com"
            },
            password: "123456"
        });
        user.save(function (_err, _user) {
            users.push(_user);
            done();
        });
    });

    it("正常登陆。", function (done) {
        var request = httpMocks.createExpressRequest({
            method: 'GET',
            url: '/search',
            body: {
                email: "login_req_0001@lz.com",
                password: "123456"
            }
        });
        var response = httpMocks.createExpressResponse();

        login.post(request, response, {}, function (_err, _user, _args) {
            testutils.check(done, function () {
                assert.notEqual(_user, null);
                _user.password.should.equal("123456");
            });
        });
    });

    it("用户不存在。", function (done) {
        var request = httpMocks.createExpressRequest({
            method: 'GET',
            url: '/search',
            body: {
                email: "login_req_9999@lz.com",
                password: "123456"
            }
        });
        var response = httpMocks.createExpressResponse();

        login.post(request, response, {}, function (_err, _user, _args) {
            testutils.check(done, function () {
                assert.equal(_user, null);
                assert.equal(_err.code, lz.Config.errors.LOGIN_USER_NOT_FOUND.code);
            });
        });
    });

    it("密码错误。", function (done) {
        var request = httpMocks.createExpressRequest({
            method: 'GET',
            url: '/search',
            body: {
                email: "login_req_0001@lz.com",
                password: "123456a"
            }
        });
        var response = httpMocks.createExpressResponse();

        login.post(request, response, {}, function (_err, _user, _args) {
            testutils.check(done, function () {
                assert.equal(_user, null);
                assert.equal(_err.code, lz.Config.errors.LOGIN_WRONG_PASSWORD.code);
            });
        });
    });

    after(function (done) {
        var tasks = [];
        users.forEach(function (_user) {
            tasks.push(function (_cb) {
                _user.delete(function () {
                    _cb(null);
                });
            });
        });
        async.series(tasks, function () {
            done();
        });
    });
});